﻿using Business.Base;
using Business.CentrifugalPump.Perf;
using Business.Common;
using Configuration;
using PLC;
using PLC.Base;
using Pumptester.ExperimentForms.Base;
using System;
using System.Collections;
using System.Drawing;
using System.Windows.Forms;
using System.Windows.Forms.DataVisualization.Charting;

namespace Pumptester.ExperimentForms.CentrifugalPump.Perf
{
    public partial class MainForm : BaseMainForm
    {
        public MainForm(Experiment experiment) : base(experiment)
        {
            InitializeComponent();
            this.Experiment = experiment;
            //this.fetch_After = dataFetch_After;
            this.dataReadHandle = dataFetch_After;

        }

        public MainForm()
        {
            //base(experiment);

            InitializeComponent();
        }

        /// <summary>
        /// 从硬件获取到数据后，计算，并且填入界面
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        private void dataFetch_After(EnvData data)
        {
            this.textBoxJKYL.Text = data.PresureIn.ToString("F2");
            this.textBoxCKYL.Text = data.PresureOut.ToString("F2");
            this.textBoxSSLL.Text = data.Flow.ToString("F2");
            this.textBoxWD.Text = data.Temperature.ToString("F2");
            this.textBoxDJZS.Text = data.Speed.ToString("F2");
            this.textBoxDL.Text = data.Current.ToString("F2");
            this.textBoxDY.Text = data.Voltage.ToString("F2");
            this.textBoxYGGL.Text = (data.ShaftPower / 1000.0).ToString("F2");
            this.textBoxGLYS.Text = data.Powerfactor.ToString("F2");
            CentrifugalPumpPerfExperimentRecord record = (CentrifugalPumpPerfExperimentRecord)this.Service.CaculateDataFromRecord(data);
            this.textBoxGDZS.Text = ((CentrifugalPumpPerfExperiment)this.Experiment).DesignRatedSpeed.ToString();
            this.textBoxZHYC.Text = record.StpHead.ToString("F2");
            this.textBoxZHLL.Text = record.StpFlow.ToString("F2");
            this.textBoxZHGL.Text = (record.StpPowerIn / 1000.0).ToString("F2");
            this.textBoxZGL.Text = (record.StpShaftPower / 1000.0).ToString("F2");
            this.textBoxJZXL.Text = record.StpGroupEfficiency.ToString("F2");
            this.textBoxXiaoLv.Text = record.StpPumpEfficiency.ToString("F2");
            this.textBoxYangCheng.Text = record.WorkingHead.ToString("F2");


        }

        private void refreshIdCell()
        {
            for (int i = 0; i < this.dataGridView.Rows.Count; i++)
            {
                this.dataGridView.Rows[i].Cells[0].Value = i + 1;
            }
        }

        #region 继承的方法和属性

        private BaseService service = new CentrifugalPumpPerfExperimentService();


        protected override BaseService Service => service;

        protected override double TransFormRadio => this.Experiment.TransFormRadio ;


        protected override void DrawChart(BaseChartData chartData)
        {
            CentrifugalPumpPerfChartData chartDatainfo = (CentrifugalPumpPerfChartData)chartData;
            Axis axisQX = this.chart.ChartAreas["perf"].AxisX;
            Axis axisHY = this.chart.ChartAreas["perf"].AxisY;
            Axis axisQX2 = this.chart.ChartAreas["powerChart"].AxisX;
            Axis axisPY = this.chart.ChartAreas["powerChart"].AxisY;
            Axis axisQX3 = this.chart.ChartAreas["effChart"].AxisX;
            Axis axisEY = this.chart.ChartAreas["effChart"].AxisY;

            axisQX.Maximum = chartDatainfo.MaxXQAxis;
            axisQX.Minimum = chartDatainfo.MinXQAxis;
            axisQX2.Maximum = chartDatainfo.MaxXQAxis;
            axisQX2.Minimum = chartDatainfo.MinXQAxis;
            axisQX3.Maximum = chartDatainfo.MaxXQAxis;
            axisQX3.Minimum = chartDatainfo.MinXQAxis;
            axisPY.Maximum = chartDatainfo.MaxYPAxis;
            axisPY.Minimum = chartDatainfo.MinYPAxis;
            axisHY.Maximum = chartDatainfo.MaxYHAxis;
            axisHY.Minimum = chartDatainfo.MinYHAxis;
            axisEY.Maximum = chartDatainfo.MaxYEAxis;
            axisEY.Minimum = chartDatainfo.MinYEAxis;

            axisQX.Interval = chartDatainfo.AxisXQInterval;
            axisQX2.Interval = chartDatainfo.AxisXQInterval;
            axisQX3.Interval = chartDatainfo.AxisXQInterval;
            axisPY.Interval = chartDatainfo.AxisYPInterval;
            axisEY.Interval = chartDatainfo.AxisYEInterval;
            axisHY.Interval = chartDatainfo.AxisYHInterval;
            chart.Series["流量扬程曲线"].Points.Clear();
            chart.Series["流量功率曲线"].Points.Clear();
            chart.Series["流量效率曲线"].Points.Clear();

            chart.Series["流量扬程曲线"].Points.DataBindXY(chartDatainfo.DrawXQList, chartDatainfo.DrawYHList);
            chart.Series["流量功率曲线"].Points.DataBindXY(chartDatainfo.DrawXQList, chartDatainfo.DrawYPList);
            chart.Series["流量效率曲线"].Points.DataBindXY(chartDatainfo.DrawXQList, chartDatainfo.DrawYEList);
            chart.Series["QHPoint"].Points.Clear();
            chart.Series["QPPoint"].Points.Clear();
            chart.Series["QEPoint"].Points.Clear();


            for (int i = 0; i < chartDatainfo.InputQEPoints.Count; i++)
            {
                double[] qePoints = chartDatainfo.InputQEPoints[i];
                double[] qhPoints = chartDatainfo.InputQHPoints[i];
                double[] qpPoints = chartDatainfo.InputQPPoints[i];
                chart.Series["QHPoint"].Points.Add(new DataPoint(qhPoints[0], qhPoints[1]));
                chart.Series["QPPoint"].Points.Add(new DataPoint(qpPoints[0], qpPoints[1]));
                chart.Series["QEPoint"].Points.Add(new DataPoint(qePoints[0], qePoints[1]));
            }

            //chart.Series["流量扬程辅助判定线"].Points.Clear();
            //chart.Series["流量功率辅助判定线"].Points.Clear();
            //chart.Series["流量效率辅助判定线"].Points.Clear();
            //double[] zeroPoint = new double[] { 0, 0 };
            //double[] headPoint = new double[] { chartDatainfo.XRatedQ, chartDatainfo.YRatedHead };
            //double[] powerPoint = new double[] { chartDatainfo.XRatedQ, chartDatainfo.YRatedPower };
            //double[] effPoint = new double[] { chartDatainfo.XRatedQ, chartDatainfo.YRatedEff };

            ArrayList flowXList = new ArrayList();
            flowXList.Add(0.0f);
            flowXList.Add(chartDatainfo.XRatedQ);
            ArrayList headYList = new ArrayList();
            headYList.Add(0.0f);
            headYList.Add(chartDatainfo.YRatedHead);
            ArrayList powerYList = new ArrayList();
            powerYList.Add(0.0f);
            powerYList.Add(chartDatainfo.YRatedPower);
            ArrayList effYList = new ArrayList();
            effYList.Add(0.0f);
            effYList.Add(chartDatainfo.YRatedEff);
            chart.Series["流量扬程辅助判定线"].Points.DataBindXY(flowXList, headYList);
            chart.Series["流量功率辅助判定线"].Points.DataBindXY(flowXList, powerYList);
            chart.Series["流量效率辅助判定线"].Points.DataBindXY(flowXList, effYList);


            ArrayList xRatedFlowRange1 = new ArrayList();
            ArrayList xRatedHeadRange = new ArrayList();

            xRatedFlowRange1.Add(chartDatainfo.FlowHeadRange[0, 0]);
            xRatedFlowRange1.Add(chartDatainfo.FlowHeadRange[1, 0]);
            xRatedHeadRange.Add(chartDatainfo.FlowHeadRange[0, 1]);
            xRatedHeadRange.Add(chartDatainfo.FlowHeadRange[1, 1]);

            chart.Series["XFlowHeadRange"].Points.Clear();
            chart.Series["XFlowHeadRange"].Points.DataBindXY(xRatedFlowRange1, xRatedHeadRange);


            ArrayList yRatedFlowRange1 = new ArrayList();
            ArrayList yRatedHeadRange = new ArrayList();

            yRatedFlowRange1.Add(chartDatainfo.FlowHeadRange[2, 0]);
            yRatedFlowRange1.Add(chartDatainfo.FlowHeadRange[3, 0]);
            yRatedHeadRange.Add(chartDatainfo.FlowHeadRange[2, 1]);
            yRatedHeadRange.Add(chartDatainfo.FlowHeadRange[3, 1]);

            chart.Series["YFlowHeadRange"].Points.Clear();
            chart.Series["YFlowHeadRange"].Points.DataBindXY(yRatedFlowRange1, yRatedHeadRange);


            ArrayList xRatedFlowRange2 = new ArrayList();
            ArrayList xRatedPowerRange = new ArrayList();

            xRatedFlowRange2.Add(chartDatainfo.FlowPowerRange[0, 0]);
            xRatedFlowRange2.Add(chartDatainfo.FlowPowerRange[1, 0]);
            xRatedPowerRange.Add(chartDatainfo.FlowPowerRange[0, 1]);
            xRatedPowerRange.Add(chartDatainfo.FlowPowerRange[1, 1]);

            chart.Series["XFlowPowerRange"].Points.Clear();
            chart.Series["XFlowPowerRange"].Points.DataBindXY(xRatedFlowRange2, xRatedPowerRange);


            ArrayList yRatedFlowRange2 = new ArrayList();
            ArrayList yRatedPowerRange = new ArrayList();

            yRatedFlowRange2.Add(chartDatainfo.FlowPowerRange[2, 0]);
            yRatedFlowRange2.Add(chartDatainfo.FlowPowerRange[3, 0]);
            yRatedPowerRange.Add(chartDatainfo.FlowPowerRange[2, 1]);
            yRatedPowerRange.Add(chartDatainfo.FlowPowerRange[3, 1]);

            chart.Series["YFlowPowerRange"].Points.Clear();
            chart.Series["YFlowPowerRange"].Points.DataBindXY(yRatedFlowRange2, yRatedPowerRange);



            ArrayList xRatedFlowRange3 = new ArrayList();
            ArrayList xRatedEffRange = new ArrayList();
            xRatedFlowRange3.Add(chartDatainfo.FlowEffRange[0, 0]);
            xRatedFlowRange3.Add(chartDatainfo.FlowEffRange[1, 0]);
            xRatedEffRange.Add(chartDatainfo.FlowEffRange[0, 1]);
            xRatedEffRange.Add(chartDatainfo.FlowEffRange[1, 1]);
            chart.Series["XFlowEffRange"].Points.Clear();
            chart.Series["XFlowEffRange"].Points.DataBindXY(xRatedFlowRange3, xRatedEffRange);


            ArrayList yRatedFlowRange3 = new ArrayList();
            ArrayList yRatedEffRange = new ArrayList();
            yRatedFlowRange3.Add(chartDatainfo.FlowEffRange[2, 0]);
            yRatedFlowRange3.Add(chartDatainfo.FlowEffRange[3, 0]);
            yRatedEffRange.Add(chartDatainfo.FlowEffRange[2, 1]);
            yRatedEffRange.Add(chartDatainfo.FlowEffRange[3, 1]);
            chart.Series["YFlowEffRange"].Points.Clear();
            chart.Series["YFlowEffRange"].Points.DataBindXY(yRatedFlowRange3, yRatedEffRange);


            /*chart.Series["流量扬程辅助判定线"].Points.Add(new DataPoint(zeroPoint[0],zeroPoint[1]));
            chart.Series["流量扬程辅助判定线"].Points.Add(new DataPoint(headPoint[0],headPoint[1]));

            chart.Series["流量功率辅助判定线"].Points.Add(new DataPoint(zeroPoint[0], zeroPoint[1]));
            chart.Series["流量功率辅助判定线"].Points.Add(new DataPoint(powerPoint[0], powerPoint[1]));


            chart.Series["流量效率辅助判定线"].Points.Add(new DataPoint(zeroPoint[0], zeroPoint[1])); 
            chart.Series["流量效率辅助判定线"].Points.Add(new DataPoint(effPoint[0], effPoint[1]));*/
        }

      

        protected override void ClearChart()
        {
            //this.chart.Series.Clear();
            chart.Series["QHPoint"].Points.Clear();
            chart.Series["QPPoint"].Points.Clear();
            chart.Series["QEPoint"].Points.Clear();
        }

        protected override void DeleteSelectRecord()
        {

            DataGridViewSelectedRowCollection selectedRows = this.dataGridView.SelectedRows;

            if (selectedRows.Count == 0)
            {
                return;
            }

            int[] ids = new int[selectedRows.Count];

            for (int i = 0; i < selectedRows.Count; i++)
            {
                if (selectedRows[i].Tag == null)
                {
                    ids[i] = -1;
                    continue;
                }
                CentrifugalPumpPerfExperimentRecord record = (CentrifugalPumpPerfExperimentRecord)selectedRows[i].Tag;
                ids[i] = record.Id;
                this.dataGridView.Rows.Remove(selectedRows[i]);
                this.Experiment.RecordList.Remove(record);
            }
            this.Service.RemoveExperimentRecordByIds(ids);
            this.CaculateAndReDrawReport();
            this.dataGridView.ClearSelection();
            refreshIdCell();


        }

        protected override void DeleteAllRecord()
        {


            for (int i = 0; i < this.dataGridView.Rows.Count; i++)
            {
                object tag = this.dataGridView.Rows[i].Tag;
                if (tag != null)
                {
                    this.dataGridView.Rows[i].Selected = true;
                }

            }
            DeleteSelectRecord();

        }


        protected override void ShowReport()
        {
            /*this.splitContainer.Panel1Collapsed = true;
            this.toolStripButtonShowList.Visible = true;
            this.toolStripShowDataButton.Visible = false;
            this.toolStripButtonShowList.Enabled = true;
            this.toolStripShowDataButton.Enabled = false;
            this.tabControl.SelectedIndex = 1;*/
        }

        protected override void ShowList()
        {
            /*this.splitContainer.Panel1Collapsed = false;
            this.toolStripButtonShowList.Visible = false;
            this.toolStripShowDataButton.Visible = true;
            this.toolStripButtonShowList.Enabled = false;
            this.toolStripShowDataButton.Enabled = true;
            this.tabControl.SelectedIndex = 0;*/
  
        }

        protected override void SaveChart()
        {
            this.chart.SaveImage(Config.ExperimentChartImageDir + "\\" + Experiment.Code + ".png", System.Drawing.Imaging.ImageFormat.Png);
        }


        protected override ExperimentRecord assignEvnDataToRecord(EnvData data)
        {
            CentrifugalPumpPerfExperimentRecord record = (CentrifugalPumpPerfExperimentRecord)this.Service.CaculateDataFromRecord(data);
            return record;
        }

        protected override void ShowRecord(ExperimentRecord experimentRecord)
        {
            CentrifugalPumpPerfExperimentRecord record = (CentrifugalPumpPerfExperimentRecord)experimentRecord;

            record.ExperimentCode = this.Experiment.Code;
            DataGridViewRow row = (DataGridViewRow)this.dataGridView.RowTemplate.Clone();

            DataGridViewTextBoxCell idCell = new DataGridViewTextBoxCell();
            idCell.Value = 0;
            idCell.Tag = false;
            

            DataGridViewTextBoxCell workFlowCell = new DataGridViewTextBoxCell();
            workFlowCell.Value = record.WorkFlow.ToString("f6");
            workFlowCell.Tag = true;
            

            DataGridViewTextBoxCell presureInCell = new DataGridViewTextBoxCell();
            presureInCell.Value = record.PresureIn.ToString("f6");
            presureInCell.Tag = true;

            DataGridViewTextBoxCell presureOutCell = new DataGridViewTextBoxCell();
            presureOutCell.Value = record.PresureOut.ToString("f6");
            presureOutCell.Tag = true;

            DataGridViewTextBoxCell voltageCell = new DataGridViewTextBoxCell();
            voltageCell.Value = record.Voltage.ToString("f6");
            voltageCell.Tag = true;

            DataGridViewTextBoxCell electricCurrentCell = new DataGridViewTextBoxCell();
            electricCurrentCell.Value = record.ElectricCurrent.ToString("f6");
            electricCurrentCell.Tag = true;

            DataGridViewTextBoxCell workHeadCell = new DataGridViewTextBoxCell();
            workHeadCell.Value = record.WorkingHead.ToString("f6");
            workHeadCell.Tag = true;


            DataGridViewTextBoxCell powerCell = new DataGridViewTextBoxCell();
            powerCell.Value = (record.WorkingPower/1000.0).ToString("f6");
            powerCell.Tag = true;

            DataGridViewTextBoxCell speedCell = new DataGridViewTextBoxCell();
            speedCell.Value = record.WorkingSpeed.ToString("f6");
            speedCell.Tag = true;

            DataGridViewTextBoxCell temperatureCell = new DataGridViewTextBoxCell();
            temperatureCell.Value = record.Temperature.ToString("f6");
            temperatureCell.Tag = true;


            DataGridViewTextBoxCell stpQCell = new DataGridViewTextBoxCell();
            stpQCell.Value = record.StpFlow.ToString("f6");
            
            stpQCell.Tag = false;


            DataGridViewTextBoxCell stpHeadCell = new DataGridViewTextBoxCell();
            stpHeadCell.Value = record.StpHead.ToString("f6");
            stpHeadCell.Tag = false;

            DataGridViewTextBoxCell stpShaftPowerCell = new DataGridViewTextBoxCell();
            stpShaftPowerCell.Value = record.StpShaftPower.ToString("f6");
            stpShaftPowerCell.Tag = false;


            DataGridViewTextBoxCell stpPumpEfficiencyCell = new DataGridViewTextBoxCell();
            stpPumpEfficiencyCell.Value = record.StpPumpEfficiency.ToString("f6");
            stpPumpEfficiencyCell.Tag = false;

            DataGridViewTextBoxCell stpGroupEfficiencyCell = new DataGridViewTextBoxCell();
            stpGroupEfficiencyCell.Value = record.StpGroupEfficiency.ToString("f6");
            stpGroupEfficiencyCell.Tag = false;

            DataGridViewTextBoxCell staticHeadCell = new DataGridViewTextBoxCell();
            staticHeadCell.Value = record.WorkingStaticHead.ToString("f6");
            staticHeadCell.Tag = false;


            DataGridViewTextBoxCell dynamicHeadHeadCell = new DataGridViewTextBoxCell();
            dynamicHeadHeadCell.Value = record.WorkingDynamicHead.ToString("f6");
            dynamicHeadHeadCell.Tag = false;

            DataGridViewTextBoxCell geoHeadHeadCell = new DataGridViewTextBoxCell();
            geoHeadHeadCell.Value = record.WorkingGeoHead.ToString("f6");
            geoHeadHeadCell.Tag = false;

            DataGridViewTextBoxCell frictionHeadCell = new DataGridViewTextBoxCell();
            frictionHeadCell.Value = record.WorkingFrictionHead.ToString("f6");
            frictionHeadCell.Tag = false;


           
            row.Cells.Add(idCell);
            row.Cells.Add(workFlowCell);
            row.Cells.Add(presureInCell);
            row.Cells.Add(presureOutCell);
            row.Cells.Add(voltageCell);
            row.Cells.Add(electricCurrentCell);
            row.Cells.Add(powerCell);
            row.Cells.Add(workHeadCell);
            row.Cells.Add(speedCell);
            row.Cells.Add(temperatureCell);
            row.Cells.Add(stpQCell);
            row.Cells.Add(stpHeadCell);
            row.Cells.Add(stpShaftPowerCell);
            row.Cells.Add(stpPumpEfficiencyCell);
            row.Cells.Add(stpGroupEfficiencyCell);
            row.Cells.Add(staticHeadCell);
            row.Cells.Add(dynamicHeadHeadCell);
            row.Cells.Add(geoHeadHeadCell);
            row.Cells.Add(frictionHeadCell);
            row.Tag = record;
            

            //this.experiment.RecordList.Add(record);
            this.dataGridView.Rows.Add(row);
            this.Service.SaveExperimentRecord(record);
            refreshIdCell();
            //计算和重画报表
            CaculateAndReDrawReport();
        }







        #endregion


        private void dataGridView_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            DataGridView dataGridView = (DataGridView)sender;

            bool canSet =(bool) dataGridView.Rows[e.RowIndex].Cells[e.ColumnIndex].Tag;
            if (!canSet)
            {
                return;
            }

            String labelText = dataGridView.Columns[e.ColumnIndex].HeaderText;

            String oldValue = dataGridView.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString();
            DataGridViewRow row = dataGridView.Rows[e.RowIndex];
            CentrifugalPumpPerfExperimentRecord record = (CentrifugalPumpPerfExperimentRecord)row.Tag;
            ValueEditForm editForm = new ValueEditForm(labelText, oldValue);

            Point point = Control.MousePosition;
            editForm.Location = point;
            var result = editForm.ShowDialog();
    
            if (DialogResult.OK == result)
            {
                try
                {
                   dataGridView.Rows[e.RowIndex].Cells[e.ColumnIndex].Value = editForm.ReturnValue;
                   
                }
                catch
                {
                    return;
                }
                switch (e.ColumnIndex)
                {
                    case 1: record.WorkFlow = Convert.ToDouble(editForm.ReturnValue); break;
                    case 2: record.PresureIn = Convert.ToDouble(editForm.ReturnValue); break;
                    case 3: record.PresureOut = Convert.ToDouble(editForm.ReturnValue);break;
                    case 4: record.Voltage = Convert.ToDouble(editForm.ReturnValue);break;
                    case 5: record.ElectricCurrent = Convert.ToDouble(editForm.ReturnValue); break;
                    case 6: record.WorkingPower = Convert.ToDouble(editForm.ReturnValue) * 1000.0; break;
                    case 7: record.WorkingHead = Convert.ToDouble(editForm.ReturnValue); break; 
                    case 8: record.WorkingSpeed = Convert.ToDouble(editForm.ReturnValue) ; break;
                    case 9: record.Temperature = Convert.ToDouble(editForm.ReturnValue); break;
                }
                //重新计算
                EnvData data = new EnvData(record.PresureIn, record.PresureOut, record.WorkFlow, record.Temperature, record.WorkingSpeed, record.Voltage, record.ElectricCurrent, record.WorkingPower, Convert.ToDouble(this.textBoxGLYS.Text));
                CentrifugalPumpPerfExperimentRecord newRecord = (CentrifugalPumpPerfExperimentRecord)this.Service.CaculateDataFromRecord(data);

                //重新刷新数据
                record.StpFlow = newRecord.StpFlow;
                record.StpHead = newRecord.StpHead;
                record.StpShaftPower = newRecord.StpShaftPower;
                record.StpPumpEfficiency = newRecord.StpPumpEfficiency;
                record.StpGroupEfficiency = newRecord.StpGroupEfficiency;
                record.WorkingStaticHead = newRecord.WorkingStaticHead;
                record.WorkingDynamicHead = newRecord.WorkingDynamicHead;   
                record.WorkingGeoHead = newRecord.WorkingGeoHead;
                record.WorkingFrictionHead = newRecord.WorkingFrictionHead;

                dataGridView.Rows[e.RowIndex].Cells[10].Value = record.StpFlow.ToString("F6");
                dataGridView.Rows[e.RowIndex].Cells[11].Value = record.StpHead.ToString("F6"); ;
                dataGridView.Rows[e.RowIndex].Cells[12].Value = record.StpShaftPower.ToString("F6"); ;
                dataGridView.Rows[e.RowIndex].Cells[13].Value = record.StpPumpEfficiency.ToString("F6"); ;
                dataGridView.Rows[e.RowIndex].Cells[14].Value = record.StpGroupEfficiency.ToString("F6");
                dataGridView.Rows[e.RowIndex].Cells[15].Value = record.WorkingStaticHead.ToString("F6");
                dataGridView.Rows[e.RowIndex].Cells[16].Value = record.WorkingDynamicHead.ToString("F6");
                dataGridView.Rows[e.RowIndex].Cells[17].Value = record.WorkingGeoHead.ToString("F6");
                dataGridView.Rows[e.RowIndex].Cells[18].Value = record.WorkingFrictionHead.ToString("F6");
                CaculateAndReDrawReport();

            }
        }

        private void chart_Click(object sender, EventArgs e)
        {

        }
    }
}
